import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'
import { Loading } from 'element-plus/es/components/loading/src/service'

let loading = null
class HttpRequest {
  private readonly baseUrl: string = import.meta.env.VITE_BASE_REQUEST_URL
  private defaultConfig() {
    return {
      baseURL: this.baseUrl,
      timeout: 10000,
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
    }
  }

  private interceptors(instance: AxiosInstance) {
    // 请求拦截
    instance.interceptors.request.use(
      (config) => {
        // 添加全局的loading..
        loading = ElLoading.service({
          fullscreen: true,
          lock: true,
          text: '正在加载...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        // 请求头携带token
        config.headers = config.headers || {}
        if (localStorage.getItem('token')) {
          config.headers.token = localStorage.getItem('token') || ''
        }
        return config
      },
      (error: any) => {
        return Promise.reject(error)
      },
    )
    //响应拦截
    instance.interceptors.response.use(
      (res) => {
        if (res.data.statusCode != '200') {
          ElMessage.error(res.data.msg)
          return Promise.reject(res.data)
        }
        // console.log('返回数据处理', res)
        loading.close()
        return res.data
      },
      (error: any) => {
        // console.log('error==>', error)
        return Promise.reject(error)
      },
    )
  }

  public request(options: AxiosRequestConfig){
    const axiosInstance = axios.create()
    let requestOptions: any = {}
    if(options['method'].toLowerCase() == 'get') {
      requestOptions = this.defaultConfig()
      requestOptions.headers = {}
      requestOptions = Object.assign(requestOptions, options)
    } else {
      requestOptions = this.defaultConfig()
      for(let conf in options) {
        if(conf == 'params') requestOptions['data'] = options[conf]
        else requestOptions[conf] = options[conf]
      }
    }
    this.interceptors(axiosInstance)
    return axiosInstance(requestOptions)
  }
}
const http = new HttpRequest()
export default http